<template>
  <div class="certificates-container">
    <div class="page-header">
      <h1>我的证书</h1>
      <p>这里展示您获得的所有课程结业证书</p>
    </div>
    
    <!-- 证书统计 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-medal"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ certificates.length }}</div>
          <div class="stat-label">获得证书</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-trophy"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ activeCertificates }}</div>
          <div class="stat-label">有效证书</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon">
          <i class="el-icon-calendar"></i>
        </div>
        <div class="stat-info">
          <div class="stat-number">{{ thisMonthCertificates }}</div>
          <div class="stat-label">本月获得</div>
        </div>
      </div>
    </div>
    
    <!-- 证书列表 -->
    <div class="certificates-section card">
      <div class="section-header">
        <h2>证书列表</h2>
        <div class="actions">
          <el-button @click="showValidateDialog = true">验证证书</el-button>
        </div>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-loading-icon />
        <p>正在加载证书...</p>
      </div>
      
      <div v-else-if="certificates.length === 0" class="empty-container">
        <i class="el-icon-document-add"></i>
        <p>您还没有获得任何证书</p>
        <p>完成课程学习并通过考试即可获得证书</p>
      </div>
      
      <div v-else class="certificates-grid">
        <div
          v-for="certificate in certificates"
          :key="certificate.id"
          class="certificate-card ka-card"
          :class="{ revoked: certificate.status === 'REVOKED' }"
        >
          <div class="certificate-header" style="background:#f6f9ff; border-bottom:1px solid #e6eefb;">
            <div class="certificate-status" :class="certificate.status.toLowerCase()">
              {{ certificate.status === 'ACTIVE' ? '有效' : '已撤销' }}
            </div>
            <div class="certificate-template">{{ getTemplateText(certificate.templateType) }}</div>
          </div>
          
          <div class="certificate-content">
            <div class="certificate-icon">
              <i class="el-icon-medal"></i>
            </div>
            
            <div class="certificate-info">
              <h3>{{ certificate.certificateName }}</h3>
              <p class="course-name">{{ certificate.courseName }}</p>
              
              <div class="certificate-meta">
                <div class="meta-item">
                  <label>证书编号：</label>
                  <span>{{ certificate.certificateNumber }}</span>
                </div>
                <div class="meta-item">
                  <label>颁发日期：</label>
                  <span>{{ formatDate(certificate.issueDate) }}</span>
                </div>
                <div class="meta-item">
                  <label>完成率：</label>
                  <span>{{ certificate.completionRate }}%</span>
                </div>
                <div v-if="certificate.finalScore" class="meta-item">
                  <label>最终成绩：</label>
                  <span>{{ certificate.finalScore }}分</span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="certificate-actions" style="border-top:1px solid #e6eefb;">
            <el-button size="small" @click="viewCertificate(certificate)">查看详情</el-button>
            <el-button v-if="certificate.pdfUrl" size="small" type="primary" @click="downloadCertificate(certificate)">
              下载PDF
            </el-button>
            <el-button size="small" @click="shareCertificate(certificate)">分享</el-button>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div v-if="total > pageSize" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 证书验证对话框 -->
    <el-dialog
      v-model="showValidateDialog"
      title="验证证书"
      width="500px"
    >
      <el-form :model="validateForm" label-width="100px">
        <el-form-item label="证书编号">
          <el-input
            v-model="validateForm.certificateNumber"
            placeholder="请输入证书编号"
          />
        </el-form-item>
        <el-form-item label="验证码">
          <el-input
            v-model="validateForm.verificationCode"
            placeholder="请输入验证码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showValidateDialog = false">取消</el-button>
        <el-button type="primary" @click="validateCertificate" :loading="validating">验证</el-button>
      </template>
    </el-dialog>
    
    <!-- 证书详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="证书详情"
      width="600px"
    >
      <div v-if="selectedCertificate" class="certificate-detail">
        <div class="detail-header">
          <i class="el-icon-medal"></i>
          <h3>{{ selectedCertificate.certificateName }}</h3>
        </div>
        
        <div class="detail-content">
          <div class="detail-item">
            <label>课程名称：</label>
            <span>{{ selectedCertificate.courseName }}</span>
          </div>
          <div class="detail-item">
            <label>证书编号：</label>
            <span>{{ selectedCertificate.certificateNumber }}</span>
          </div>
          <div class="detail-item">
            <label>验证码：</label>
            <span>{{ selectedCertificate.verificationCode }}</span>
          </div>
          <div class="detail-item">
            <label>颁发日期：</label>
            <span>{{ formatDate(selectedCertificate.issueDate) }}</span>
          </div>
          <div class="detail-item">
            <label>完成率：</label>
            <span>{{ selectedCertificate.completionRate }}%</span>
          </div>
          <div v-if="selectedCertificate.finalScore" class="detail-item">
            <label>最终成绩：</label>
            <span>{{ selectedCertificate.finalScore }}分</span>
          </div>
          <div v-if="selectedCertificate.issuerName" class="detail-item">
            <label>颁发机构：</label>
            <span>{{ selectedCertificate.issuerName }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { certificateApi, type Certificate } from '@/api/certificate'

const certificates = ref<Certificate[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

const showValidateDialog = ref(false)
const showDetailDialog = ref(false)
const selectedCertificate = ref<Certificate>()
const validating = ref(false)

const validateForm = reactive({
  certificateNumber: '',
  verificationCode: ''
})

// 计算属性
const activeCertificates = computed(() => {
  return certificates.value.filter(cert => cert.status === 'ACTIVE').length
})

const thisMonthCertificates = computed(() => {
  const thisMonth = new Date().getMonth()
  const thisYear = new Date().getFullYear()
  return certificates.value.filter(cert => {
    const issueDate = new Date(cert.issueDate)
    return issueDate.getMonth() === thisMonth && issueDate.getFullYear() === thisYear
  }).length
})

// 获取模板类型文本
const getTemplateText = (template: string) => {
  const templateMap = {
    BASIC: '基础版',
    ADVANCED: '高级版',
    PROFESSIONAL: '专业版'
  }
  return templateMap[template as keyof typeof templateMap] || template
}

// 格式化日期
const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 加载证书列表
const loadCertificates = async () => {
  try {
    loading.value = true
    const res = await certificateApi.getMy({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    console.log('证书API响应:', res) // 调试日志
    certificates.value = res.content || []
    total.value = res.totalElements || 0
  } catch (error) {
    console.error('获取证书列表失败:', error)
    ElMessage.error('获取证书列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadCertificates()
}

// 查看证书详情
const viewCertificate = (certificate: Certificate) => {
  selectedCertificate.value = certificate
  showDetailDialog.value = true
}

// 下载证书
const downloadCertificate = (certificate: Certificate) => {
  if (certificate.pdfUrl) {
    window.open(certificate.pdfUrl, '_blank')
  } else {
    ElMessage.warning('PDF文件不存在')
  }
}

// 分享证书
const shareCertificate = (certificate: Certificate) => {
  const shareUrl = `${window.location.origin}/certificate/validate?number=${certificate.certificateNumber}&code=${certificate.verificationCode}`
  
  if (navigator.share) {
    navigator.share({
      title: certificate.certificateName,
      text: `我获得了《${certificate.courseName}》的结业证书！`,
      url: shareUrl
    })
  } else {
    // 复制到剪贴板
    navigator.clipboard.writeText(shareUrl).then(() => {
      ElMessage.success('分享链接已复制到剪贴板')
    }).catch(() => {
      ElMessage.error('复制失败，请手动复制：' + shareUrl)
    })
  }
}

// 验证证书
const validateCertificate = async () => {
  if (!validateForm.certificateNumber || !validateForm.verificationCode) {
    ElMessage.warning('请输入证书编号和验证码')
    return
  }
  
  try {
    validating.value = true
    const res = await certificateApi.validate(validateForm.certificateNumber, validateForm.verificationCode)
    ElMessage.success('证书验证成功')
    
    // 显示验证结果
    selectedCertificate.value = res.data
    showValidateDialog.value = false
    showDetailDialog.value = true
    
    // 清空表单
    validateForm.certificateNumber = ''
    validateForm.verificationCode = ''
  } catch (error) {
    console.error('证书验证失败:', error)
    ElMessage.error('证书验证失败，请检查证书编号和验证码')
  } finally {
    validating.value = false
  }
}

onMounted(() => {
  loadCertificates()
})
</script>

<style scoped>
.certificates-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
}

.page-header p {
  color: #666;
  margin: 0;
}

.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  line-height: 1;
}

.stat-label {
  color: #666;
  font-size: 14px;
  margin-top: 4px;
}

.certificates-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.section-header h2 {
  margin: 0;
  color: #333;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.empty-container i {
  font-size: 48px;
  margin-bottom: 20px;
  color: #ddd;
}

.certificates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.certificate-card {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.certificate-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.certificate-card.revoked {
  opacity: 0.7;
  background: #f9f9f9;
}

.certificate-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f9f9f9;
  border-bottom: 1px solid #eee;
}

.certificate-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.certificate-status.active {
  background: #f0f9ff;
  color: #1890ff;
}

.certificate-status.revoked {
  background: #fff2f0;
  color: #ff4d4f;
}

.certificate-template {
  color: #666;
  font-size: 12px;
}

.certificate-content {
  padding: 20px;
  display: flex;
  gap: 15px;
}

.certificate-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background: linear-gradient(135deg, #ffd700, #ffb300);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  flex-shrink: 0;
}

.certificate-info {
  flex: 1;
}

.certificate-info h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 16px;
}

.course-name {
  color: #666;
  margin: 0 0 15px 0;
  font-size: 14px;
}

.certificate-meta {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.meta-item {
  display: flex;
  font-size: 12px;
}

.meta-item label {
  color: #666;
  min-width: 70px;
}

.meta-item span {
  color: #333;
}

.certificate-actions {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.certificate-detail {
  text-align: center;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-header i {
  font-size: 48px;
  color: #ffd700;
  margin-bottom: 10px;
}

.detail-header h3 {
  margin: 0;
  color: #333;
}

.detail-content {
  text-align: left;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item label {
  min-width: 100px;
  color: #666;
  font-weight: bold;
}

.detail-item span {
  color: #333;
}
</style>

